﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZP.Common;
using ZP.DTO.Common;
using ZP.IBLL;

namespace ZCSBZPJ.Controllers
{
    public class LoginController : Controller
    {
        public Ifz_sys_userService _fz_sys_userService { get; set; }
        //public LoginController(Ifz_sys_userService fz_sys_userService)
        //{
        //    this._fz_sys_userService = fz_sys_userService;
        //}

        public ActionResult Index(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        /// <summary>
        /// 是否需要重新登录
        /// </summary>
        /// <returns></returns>
        public JsonResult IsLogin()
        {
            var isLogin = Session[ZPCommon.SESSION_Login];
            if (isLogin == null)
            {
                return Json(false);
            }
            return Json(true);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            Session[ZPCommon.SESSION_Login] = null;
            return RedirectToAction("index", "login");
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JsonResult Logon(LoginModel model)
        {
            ResultData<string> result = new ResultData<string>();
            try
            {
                bool isVCode = string.IsNullOrWhiteSpace(ZPCommon.isVerification) ? true : ZPCommon.isVerification == "1" ? true : false;
                if (isVCode)
                {
                    bool DxVerify = DxVerifyToken(model.Token);
                    if (!DxVerify)
                    {
                        result.Message = TipsMessage.LOGIN_图形码验证不通过;
                    }
                }

                if (string.IsNullOrWhiteSpace(result.Message))
                {
                    //System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                    //stopwatch.Start();
                    //******** 检测代码块 Begin ******** 
                    UserLoginDTO user = _fz_sys_userService.Login(model);
                    //******** 检测代码块 End ******** 
                    //stopwatch.Stop();
                    //Logger.Logger.Info("耗时1:" + stopwatch.Elapsed.TotalSeconds);
                    if (user == null)
                    {
                        result.Message = TipsMessage.LOGIN_用户名或密码错误;
                        int errorCount = _fz_sys_userService.LoginErrorCount(model, false);//记录登录错误次数
                        if (errorCount >= ZPCommon.ZP_LOGIN_ERROR_MAX_COUNT)
                        {
                            result.Message = string.Format(TipsMessage.LOGIN_输入登录错误密码已超过次数, ZPCommon.ZP_LOGIN_ERROR_MAX_COUNT);
                        }
                    }
                    else if (user.isLocked.HasValue && user.isLocked.Value == (int)ZPUserLockedType.Locked)
                    {
                        result.Message = TipsMessage.LOGIN_该用户被锁定;
                    }
                    else if (user.state.HasValue && user.state.Value == (int)ZPFlagType.NO)
                    {
                        result.Message = TipsMessage.LOGIN_该用户被停用;
                    }
                    else
                    {
                        int errorCount = _fz_sys_userService.LoginErrorCount(model, true);//重置登录错误次数
                        result.SubmitResult = true;
                        Session[ZPCommon.SESSION_Login] = user;
                        Session.Timeout = 30;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return Json(result);
        }

        /// <summary>
        /// 顶象验证码
        /// </summary>
        /// <returns></returns>
        public bool DxVerifyToken(string token)
        {
            // 在您的项目中添加DxCsharpSDK.dll引用
            String appId = ZPCommon.ZP_DX_APPID;
            String appSecret = ZPCommon.ZP_DX_APPSecret;
            DxCsharpSDK.Captcha captcha = new DxCsharpSDK.Captcha(appId, appSecret);
            //特殊情况需要额外指定服务器,可以在这个指定，默认情况下不需要设置
            //captcha.SetCaptchaUrl("http://cap.dingxiang-inc.com/api/tokenVerify");
            //设置超时时间，单位毫秒，默认2秒 
            //captcha.SetTimeOut(2000);
            DxCsharpSDK.CaptchaResponse response = captcha.VerifyToken(token);
            //确保验证状态是SERVER_SUCCESS，SDK中有容错机制，在网络出现异常的情况会返回通过(IE会验证不通过,response.result=false，原因未知)
            if (response.captchaStatus == "SERVER_SUCCESS" && response.result)
            {
                /**token验证通过，继续其他流程**/
                return true;
            }
            else
            {
                /**token验证失败，业务系统可以直接阻断该次请求或者继续弹验证码**/
                return false;
            }
        }


    }
}